﻿using Fonour.Application.Dtos;
using Fonour.Application.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Fonour.MVC.Controllers
{
    public class RoleController : FonourControllerBase
    {
        public readonly IRoleService _roleService;

        public RoleController(IRoleService roleService)
        {
            this._roleService = roleService;
        }

        public IActionResult Index()
        {
            return View();
        }

        public async Task<IActionResult> GetAllPageListAsync(int startPage, int pageSize)
        {
            var result = await this._roleService.GetPageListAsync(startPage, pageSize, null, p => p.Code);
            return Json(new
            {
                rowCount = result.TotalCount,
                pageCount = Math.Ceiling(Convert.ToDecimal(result.TotalCount) / pageSize),
                rows = result.DataList,
            });
        }

        public async Task<IActionResult> GetMenusByRoleAsync(Guid roleId)
        {
            var result = await this._roleService.GetAllMenuListByRoleAsync(roleId);
            return Json(result);
        }

        public IActionResult SavePermission(Guid roleId, List<RoleMenuDto> roleMenus)
        {
            if (this._roleService.UpdateRoleMenu(roleId, roleMenus))
            {
                return Json(new { Result = "Success" });
            }

            return Json(new { Result = "Faild" });
        }

        /// <summary>
        /// 新增或编辑功能
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Edit(RoleDto dto)
        {
            if (!ModelState.IsValid)
            {
                return Json(new
                {
                    Result = "Faild",
                    Message = GetModelStateError()
                });
            }

            if (dto.Id == Guid.Empty)
            {
                dto.CreateTime = DateTime.Now;

                string userId = string.Empty;
                var loginUser = HttpContext.User;
                if (loginUser.Claims.Any(p => p.Type == ClaimTypes.Sid))
                {
                    userId = loginUser.Claims.FirstOrDefault(p => p.Type == ClaimTypes.Sid).Value;
                }

                dto.CreateUserId = Guid.Parse(userId);
            }

            if (_roleService.InsertOrUpdate(dto))
            {
                return Json(new { Result = "Success" });
            }

            return Json(new { Result = "Faild" });
        }

        [HttpPost]
        public IActionResult DeleteMuti(string ids)
        {
            try
            {
                string[] idArray = ids.Split(',');
                List<Guid> delIds = new List<Guid>();
                foreach (string id in idArray)
                {
                    delIds.Add(Guid.Parse(id));
                }

                _roleService.DeleteBatch(delIds);
                return Json(new
                {
                    Result = "Success"
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    Result = "Faild",
                    Message = ex.Message
                });
            }
        }

        [HttpPost]
        public IActionResult Delete(Guid id)
        {
            try
            {
                _roleService.Delete(id);
                return Json(new
                {
                    Result = "Success"
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    Result = "Faild",
                    Message = ex.Message
                });
            }
        }

        public async Task<ActionResult> Get(Guid id)
        {
            var dto = await _roleService.GetAsync(id);
            return Json(dto);
        }
    }
}
